<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="80px">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateValue"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['12:00:00', '08:00:00']"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
        />
      </el-form-item>
      <el-form-item label="老人名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入老人名字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          v-hasPermission="['personal:healthy:add']"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          v-hasPermission="['personal:healthy:export']"
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          action="upload"
          class="upload-demo"
          v-hasPermission="['personal:healthy:upload']"
          :http-request="handleUpload"
          name="file"
          :show-file-list="false"
          accept=".xls, .xlsx"
          :before-upload="handleBeforeUpload"
        >
          <el-button
            type="success"
            plain
            icon="el-icon-upload"
            size="mini"
          >导入</el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="healthyList" style="width: 100%">
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column prop="name" label="名字" align="center" show-overflow-tooltip />
      <el-table-column prop="identityId" label="身份证号" align="center" show-overflow-tooltip />
      <el-table-column prop="bloodPressure" label="血压/mmHg" align="center">
        <template slot-scope="scope">
          {{ scope.row.bloodPressure ? scope.row.bloodPressure + 'mmHg': '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="vitalCapacity" label="肺活量/ml" align="center">
        <template slot-scope="scope">
          {{ scope.row.vitalCapacity ? scope.row.vitalCapacity + 'ml' : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="bloodFatCholesterol" label="(血脂胆固醇)mmol/L" align="center">
        <template slot-scope="scope">
          {{ scope.row.bloodFatCholesterol ? scope.row.bloodFatCholesterol + 'mmol/L' : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="bloodFatTriglyceride" label="(血脂甘油三酯)mmol/L" align="center">
        <template slot-scope="scope">
          {{ scope.row.bloodFatTriglyceride ? scope.row.bloodFatTriglyceride + 'mmol/L' : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="heartRate" label="心率(次/分)" align="center">
        <template slot-scope="scope">
          {{ scope.row.heartRate ? scope.row.heartRate + '次/分' : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="uricAcid" label="尿酸(mmol/L)" align="center">
        <template slot-scope="scope">
          {{ scope.row.uricAcid ? scope.row.uricAcid + 'mmol/L' : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="bloodSugar" label="血糖mg/dl" align="center">
        <template slot-scope="scope">
          {{ scope.row.bloodSugar ? scope.row.bloodSugar + 'mg/dl' : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="measurementTime" label="测量时间" align="center" />
      <el-table-column prop="measureName" label="测量人" align="center" />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            v-hasPermission="['personal:healthy:update']"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            v-hasPermission="['personal:healthy:delete']"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      :current-page.sync="queryParams.pageNum"
      @current-change="getList"
      @size-change="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-select
                ref="elderlyName"
                v-model="elderly"
                style="width:100%"
                placeholder="请输入老人姓名"
                filterable
                remote
                default-first-option
                clearable
                :remote-method="(query) => { searchInput(query) }"
                :loading="loading"
                @change="selectChange"
              >
                <el-option
                  v-for="item in elderlyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="identityId">
              <el-input v-model="form.identityId" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="血压" prop="bloodPressure">
              <el-input-number v-model="form.bloodPressure" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血糖" prop="bloodSugar">
              <el-input-number v-model="form.bloodSugar" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="血脂(胆固醇)" prop="bloodFatCholesterol">
              <el-input-number v-model="form.bloodFatCholesterol" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血脂(甘油三酯)" prop="bloodFatTriglyceride">
              <el-input-number v-model="form.bloodFatTriglyceride" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="心率" prop="heartRate">
              <el-input-number v-model="form.heartRate" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="尿酸" prop="uricAcid">
              <el-input-number v-model="form.uricAcid" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="肺活量" prop="vitalCapacity">
              <el-input-number v-model="form.vitalCapacity" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测量时间" prop="measurementTime">
              <el-date-picker
                v-model="form.measurementTime"
                type="datetime"
                placeholder="请选择测量时间"
                default-time="12:00:00"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="测量人" prop="measureName">
              <el-input v-model="form.measureName" placeholder="请输入测量人名字" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  addHealthy, delHealthy,
  exportHealthy,
  getElderly, getHealthy,
  listHealthy,
  updateHealthy,
  uploadHealthy
} from '@/api/personal/healthy'

export default {
  name: 'Healthy',
  data() {
    return {
      exportLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        startTime: '',
        endTime: ''
      },
      dateValue: [],
      loading: true,
      healthyList: [],
      total: 0,
      elderly: null,
      form: {
        name: '',
        identityId: '',
        bloodPressure: '',
        vitalCapacity: '',
        bloodSugar: '',
        measurementTime: '',
        measureName: '',
        bloodFatCholesterol: '',
        bloodFatTriglyceride: '',
        heartRate: '',
        uricAcid: ''
      },
      rules: {

      },
      elderlyList: [],
      title: '',
      open: false
    }
  },
  watch: {
    dateValue: {
      handler(newVal, oldVal) {
        if (newVal != null) {
          this.queryParams.startTime = newVal[0]
          this.queryParams.endTime = newVal[1]
        } else {
          this.queryParams.startTime = ''
          this.queryParams.endTime = ''
        }
      },
      immediate: false
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listHealthy(this.queryParams).then((res) => {
        this.healthyList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleAdd() {
      this.reset()
      this.title = '添加健康记录'
      this.open = true
    },
    handleUpdate(item) {
      this.title = '修改健康记录'
      getHealthy(item.id).then((res) => {
        this.form = res
        if (res.elderly) {
          this.elderly = res.elderly
          this.elderlyList.push(res.elderly)
        }
        this.open = true
      })
    },
    handleDelete(item) {
      const ids = item.id
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function() {
          return delHealthy(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    searchInput(query) {
      getElderly({ name: query }).then((res) => {
        this.elderlyList = res
      })
    },
    selectChange(item) {
      this.form.identityId = item.identityId
    },
    submitForm() {
      this.$refs['form'].validate((valid, error) => {
        if (valid) {
          this.form.name = this.elderly.name
          if (this.form.id !== undefined) {
            updateHealthy(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addHealthy(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        } else {
          return
        }
      })
      this.reset()
    },
    cancel() {
      this.reset()
      this.open = false
    },
    reset() {
      this.form = {
        name: '',
        identityId: '',
        bloodPressure: '',
        vitalCapacity: '',
        bloodSugar: '',
        measurementTime: '',
        measureName: '',
        bloodFatCholesterol: '',
        bloodFatTriglyceride: '',
        heartRate: '',
        uricAcid: ''
      }
      this.elderly = null
      this.elderlyList = []
    },
    handleExport() {
      this.$modal.confirm('是否确认导出所有数据？').then(() => {
        this.exportLoading = true
        return exportHealthy()
      }).then(response => {
        // this.$download.name(response.msg)
        this.exportLoading = false
      }).catch(() => {})
    },
    handleUpload(file) {
      const loading = this.$loading({
        lock: true,
        text: '正在上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      uploadHealthy(file.file).then((response) => {
        loading.close()
        this.$message.success('上传成功')
        this.getList()
      }).catch(error => {
        loading.close()
        this.$message.error(error.msg)
      })
    },
    handleBeforeUpload(file) {
      var suffix = file.name.substr(file.name.lastIndexOf('.'))
      if (suffix !== '.xls' && suffix !== '.xlsx') {
        this.$message.error('请上传Excel文件,后缀.xls .xlsx')
      }
    }
  }
}
</script>

<style scoped>

</style>
